{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "import yaml\n",
    "import random\n",
    "from aip import AipSpeech\n",
    "root_dir = \"/xiaobai/\"\n",
    "sys.path.append(root_dir)\n",
    "from xiaobai import XiaoBai,BaseSkill"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "find MJ_HT_V1\n",
      "58:2d:34:30:36:d1\n"
     ]
    }
   ],
   "source": [
    "from bluepy.btle import Scanner, DefaultDelegate\n",
    "\n",
    "class ScanDelegate(DefaultDelegate):\n",
    "    def __init__(self):\n",
    "        DefaultDelegate.__init__(self)\n",
    "\n",
    "    def handleDiscovery(self, dev, isNewDev, isNewData):\n",
    "        if isNewDev:\n",
    "            pass\n",
    "            #print(\"Discovered device \",  dev.addr)\n",
    "        elif isNewData:\n",
    "            pass\n",
    "            #print(\"Received new data from\", dev.addr)\n",
    "\n",
    "def find_dev(name=\"\"):\n",
    "    scanner = Scanner().withDelegate(ScanDelegate())\n",
    "    devices = scanner.scan(10.0)\n",
    "\n",
    "    for dev in devices:\n",
    "        #print(\"Device %s (%s), RSSI=%d dB\" % (dev.addr, dev.addrType, dev.rssi) )\n",
    "        for (adtype, desc, value) in dev.getScanData():\n",
    "            if desc == \"Complete Local Name\" and value==name:\n",
    "                print(\"find MJ_HT_V1\")\n",
    "                return dev.addr\n",
    "    return None\n",
    "if __name__ == '__main__':\n",
    "    print(find_dev('MJ_HT_V1'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "温度：27.9℃，湿度：18.9%\n"
     ]
    }
   ],
   "source": [
    "from bluepy import btle\n",
    "import re\n",
    "\n",
    "class XiomiHygroThermoDelegate(object):\n",
    "    def __init__(self):\n",
    "        self.temperature = None\n",
    "        self.humidity = None\n",
    "        self.received = False\n",
    "        self.count = 0\n",
    "\n",
    "    def handleNotification(self, cHandle, data):\n",
    "        #print(data)\n",
    "        if cHandle == 14:\n",
    "            self.count = self.count + 1\n",
    "            if self.count % 2 == 1 : \n",
    "                return\n",
    "            else:\n",
    "                m = re.search('T=([\\d\\.]*)\\s+?H=([\\d\\.]*)', ''.join(map(chr, data)))\n",
    "                self.temperature = m.group(1)\n",
    "                self.humidity = m.group(2)\n",
    "                #print(\"温度：\"+self.temperature+\"℃，湿度：\"+self.humidity+\"%\")\n",
    "                self.received = True\n",
    "            \n",
    "class SensorSkill(BaseSkill):\n",
    "    def __init__(self):\n",
    "        self.address = \"58:2d:34:30:36:d1\"\n",
    "    #继承BaseSkill类，必须定义has_intent和action方法\n",
    "    def has_intent(self,text=\"\"):\n",
    "        for keyword in [\"温度\",\"湿度\",\"温湿度\",\"气温\"]:\n",
    "            if text.find(keyword)>= 0:\n",
    "                return True\n",
    "        return False\n",
    "    def action(self,text=\"\",callback=print):\n",
    "        try:\n",
    "            p = btle.Peripheral(self.address)\n",
    "            delegate = XiomiHygroThermoDelegate()\n",
    "            p.withDelegate( delegate )\n",
    "            p.writeCharacteristic(0x10, bytearray([1, 0]), True)\n",
    "            while not delegate.received:\n",
    "                p.waitForNotifications(4.0)\n",
    "            temperature = delegate.temperature\n",
    "            humidity = delegate.humidity\n",
    "            callback(\"温度：\"+temperature+\"℃，湿度：\"+humidity+\"%\")\n",
    "        except:\n",
    "            callback(\"出错了呢\")\n",
    "if __name__ == '__main__':\n",
    "    import time\n",
    "    s = SensorSkill()\n",
    "    s.handle(\"温度是多少\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Listening...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:snowboy:Keyword 1 detected at time: 2019-05-13 14:47:15\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你：温度湿度\n",
      "小白：温度：28.5℃，湿度：19.1%\n"
     ]
    }
   ],
   "source": [
    "keyword_model = root_dir+'resources/小白.pmdl'\n",
    "xiaobai = XiaoBai(keyword_model=keyword_model)\n",
    "xiaobai.add_skill(SensorSkill())\n",
    "xiaobai.listen_for_keyword()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
